import json
import os
import logging

# 创建日志记录器
def create_logger():
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s | 文件:%(filename)s,函数:%(funcName)s')
    return logging

# 加载语言数据
def load_language_data():
    current_dir = os.getcwd()
    logging.info(f"当前工作目录: {current_dir}")
    
    language_file_path = os.path.join(current_dir, 'language.json')
    logging.info(f"语言文件路径: {language_file_path}")

    if os.path.exists(language_file_path) and os.path.getsize(language_file_path) > 0:
        try:
            with open(language_file_path, 'r', encoding='utf-8') as f:  # 指定文件编码为 utf-8
                language_data = json.load(f)
                logging.info("语言数据加载成功")
                return language_data
        except json.JSONDecodeError as e:
            logging.error(f"JSON 解析错误: {e}")
    else:
        logging.warning("语言文件不存在或为空")

    return None  # 如果文件不存在或解析失败，返回 None

# 写入语言数据
def write_language_data(language_data, key, value):
    if language_data is None:
        logging.error("语言数据为空，无法写入")
        return

    language_data[key] = value
    try:
        with open('language.json', 'w', encoding='utf-8') as f:
            json.dump(language_data, f, ensure_ascii=False, indent=4)
        logging.info("语言数据写入成功")
    except Exception as e:
        logging.error(f"写入语言数据时发生错误: {e}")

# 初始化日志和语言数据
logging = create_logger()
language_data = load_language_data()

if language_data is None:
    logging.warning("语言数据加载失败，将使用默认语言设置")
    language_data = {
        "current_language": "en",  # 默认语言设置为英文
        "zh": {},
        "en": {}
    }